import logging
from logging import Logger
from datetime import datetime
from logging.handlers import RotatingFileHandler

from ctaf_core.ctaf_utils.file_process_util import get_file_path

from ctaf_core.ctaf_resources.ctaf_settings import CTAFsettings
from pathlib import Path


from ctaf_core.ctaf_objects.base_exception import CTAFbaseException


class LogRecorder:
    """
    Processes log
    """

    def __init__(self) -> None:
        """"""

        if not CTAFsettings.get_setting("log.active"):
            return

        self.level: int = CTAFsettings.get_setting("log.level")
        self.rotating_file_max_bytes: int = CTAFsettings.get_setting("log.rotatingFileMaxBytes")
        self.rotating_file_backup_count: int = CTAFsettings.get_setting("log.rotatingFileBackupCount")

        self.logger: Logger = logging.getLogger("CATS")
        self.logger.setLevel(self.level)

        self.formatter: logging.Formatter = logging.Formatter(
            "%(asctime)s  %(levelname)s: %(message)s"
        )

        if CTAFsettings.get_setting("log.console"):
            self.add_console_handler()

        if CTAFsettings.get_setting("log.file"):
            self.add_file_handler()


    def add_console_handler(self) -> None:
        """
        Add console output of log.
        """
        console_handler: logging.StreamHandler = logging.StreamHandler()
        console_handler.setLevel(self.level)
        console_handler.setFormatter(self.formatter)
        self.logger.addHandler(console_handler)

    def add_file_handler(self) -> None:
        """
        Add rotating file output of log.
        """
        today_date: str = datetime.now().strftime("%Y%m%d")
        filename: str = f"cats_{today_date}.log"
        log_path: Path = get_file_path("log")
        file_path: Path = log_path.joinpath(filename)
        file_handler = RotatingFileHandler(file_path, maxBytes=self.rotating_file_max_bytes, backupCount=self.rotating_file_backup_count)

        file_handler.setLevel(self.level)
        file_handler.setFormatter(self.formatter)
        self.logger.addHandler(file_handler)

    def write_debug_log(self, message: str = None, exception: CTAFbaseException = None):
        self.logger.debug(message, exc_info=exception)

    def write_info_log(self, message: str = None, exception: CTAFbaseException = None):
        self.logger.info(message, exc_info=exception)

    def write_warn_log(self, message: str = None, exception: CTAFbaseException = None):
        self.logger.warning(message, exc_info=exception)

    def write_error_log(self, message: str = None, exception: CTAFbaseException = None):
        self.logger.error(message, exc_info=exception)

    def write_critical_log(self,message: str = None, exception: CTAFbaseException = None):
        self.logger.critical(message, exc_info=exception)


class LoggerFactory:

       __logger_instance = None

       @staticmethod
       def get_logger()->LogRecorder:
           if LoggerFactory.__logger_instance is None:
               LoggerFactory.__logger_instance = LogRecorder()
           return LoggerFactory.__logger_instance
